<?php

//<meta property="gs:title" content="a funny photo" />
//<meta property="gs:type" content="picture" />
//<meta property="gs:uri" content="" />
//<meta property="gs:thumb_image" content="" />
//<meta property="gs:app_name" content="" />
//<meta property="gs:app_id" content="675354505" />

define('GGS_SO_TYPE_LINK', 1);
define('GGS_SO_TYPE_PHOTO', 2);
define('GGS_SO_TYPE_GAME', 3);

define('GGS_SA_LIKE', 1);
define('GGS_SA_RATING', 2);
define('GGS_SA_COMMENT', 3);

class GgsSocialObjects {

    public function __construct() {
        ;
    }

    public static function hashFromUrl($url) {
        return hash('sha256', strtolower($url));
    }

    private static function updateSocialObjects($user_id, $url, $action_type = GGS_SA_LIKE, $isLike = TRUE, $rating = 0, $comment = '', $obj_type = GGS_SO_TYPE_LINK, $title = "", $thumb_image = "") {
        if ($user_id <= 0) {
            return FALSE;
        }
        if ($obj_type != GGS_SO_TYPE_LINK && $obj_type != GGS_SO_TYPE_PHOTO && $obj_type != GGS_SO_TYPE_GAME) {
            return FALSE;
        }
        if ($action_type != GGS_SA_LIKE && $action_type != GGS_SA_RATING && $action_type != GGS_SA_COMMENT) {
            return FALSE;
        }

        //prepare params
        $hash = self::hashFromUrl($url);
        $comment = mysql_real_escape_string($comment);
        $url = mysql_real_escape_string($url);
        $title = mysql_real_escape_string($title);
        $thumb_image = mysql_real_escape_string($thumb_image);
        $rating = intval($rating);
        $user_id = intval($user_id);

        $total_rating = 0;
        $avg_rating = 0;
        $total_like = 0;
        $total_comment = 0;

        $get_query = "SELECT object_id,total_rating,avg_rating,total_like,total_comment FROM gs_sa_objects WHERE hash = '$hash'";
        $rs = safe_select_query($get_query);

        if (empty($rs)) {
            //first object is born
            $add_query = "INSERT INTO gs_sa_objects(hash, type, url, title, thumb_image)
                VALUES('$hash', $obj_type, '$url', '$title', '$thumb_image' )";
            $object_id = safe_insert_query($add_query);

            if ($object_id != false) {
                $rs = safe_select_query($get_query);
            }
        }

        if (!empty($rs)) {
            $record = $rs[0];
            $object_id = $record->object_id;
            $total_rating = intval($record->total_rating);
            $avg_rating = floatval($record->avg_rating);
            $total_like = intval($record->total_like);
            $total_comment = intval($record->total_comment);

            $user_activity_update = false;

            //first user do action
            if ($action_type === GGS_SA_LIKE) {
                //delete and insert   
                if ($isLike) {
                    safe_delete_query("DELETE FROM gs_sa_user_activity WHERE object_id = $object_id AND action_type=$action_type AND user_id=$user_id");
                    if (mysql_affected_rows() === 0) {
                        $total_like += 1;
                    }
                    $add_query2 = "INSERT INTO gs_sa_user_activity(object_id, user_id, action_type, rating, comment)
                           VALUES($object_id, $user_id, $action_type, 0, '' )";
                    safe_insert_query($add_query2);
                    $user_activity_update = mysql_affected_rows() > 0;
                } else {
                    safe_delete_query("DELETE FROM gs_sa_user_activity WHERE object_id = $object_id AND action_type=$action_type AND user_id=$user_id");
                    if (mysql_affected_rows() > 0) {
                        $total_like -= 1;
                        $user_activity_update = TRUE;
                    }
                }
            } else if ($action_type === GGS_SA_COMMENT) {
                $total_comment += 1;
                //delete and insert
                $add_query2 = "INSERT INTO gs_sa_user_activity(object_id, user_id, action_type, rating, comment)
                           VALUES($object_id, $user_id, $action_type, 0, '$comment' )";
                safe_insert_query($add_query2);
                $user_activity_update = mysql_affected_rows() > 0;
            } else if ($action_type === GGS_SA_RATING) {
                //delete and insert
                //NOT IMPLEMENT
//                safe_delete_query("DELETE FROM gs_sa_user_activity WHERE object_id = $object_id AND action_type=$action_type AND user_id=$user_id");
//                if (mysql_affected_rows() === 0) {
//                    $total_rating += 1;
//                    $avg_rating = ($avg_rating + $rating) / $total_rating;
//                }
//                $add_query2 = "INSERT INTO gs_sa_user_activity(object_id, user_id, action_type, rating, comment)
//                           VALUES($object_id, $user_id, $action_type, $rating, '' )";
//                safe_insert_query($add_query2);
//                $user_activity_update = mysql_affected_rows() > 0;
            }

            if ($user_activity_update) {
                $update_query = "UPDATE gs_sa_objects SET total_rating=$total_rating, avg_rating=$avg_rating, total_like=$total_like,total_comment=$total_comment WHERE object_id=$object_id";
                safe_update_query($update_query);
                if (mysql_affected_rows() > 0) {
                    return TRUE;
                }
            }
        }
        return FALSE;
    }

    ///////////////////////////
    ////////  RATING  ////////
    ///////////////////////////

    public static function doRating($user_id, $url, $rating, $obj_type = GGS_SO_TYPE_LINK, $title = "", $thumb_image = "") {
        return self::updateSocialObjects($user_id, $url, GGS_SA_RATING, FALSE, $rating, '', $obj_type, $title, $thumb_image);
    }

    ///////////////////////////
    ////////  COMMENT  ////////
    ///////////////////////////

    public static function postComment($user_id, $url, $comment, $obj_type = GGS_SO_TYPE_LINK, $title = "", $thumb_image = "") {
        return self::updateSocialObjects($user_id, $url, GGS_SA_COMMENT, FALSE, 0, $comment, $obj_type, $title, $thumb_image);
    }

    public static function removeComment($url, $comment_id) {
        $hash = self::hashFromUrl($url);
        $rs = safe_select_query("SELECT total_comment FROM gs_sa_objects WHERE hash = '$hash'");
        if (!empty($rs)) {
            safe_delete_query("DELETE FROM gs_sa_user_activity WHERE id = $comment_id");
            if (mysql_affected_rows() > 0) {
                $total_comment = intval($rs[0]->total_comment) - 1;
                $update_query = "UPDATE gs_sa_objects SET total_comment=$total_comment WHERE hash='$hash'";
                safe_update_query($update_query);
                if (mysql_affected_rows() > 0) {
                    return TRUE;
                }
            }
        }
        return FALSE;
    }

    public static function getComments($url,$start =0, $limit = 5) {
        $action_type = GGS_SA_COMMENT;
        $hash = self::hashFromUrl($url);
        $elggUserTable = '3lGG_users_entity';

        $q = "SELECT a.*, $elggUserTable.name
            FROM
            (
            SELECT gs_sa_user_activity.id as comment_id, gs_sa_user_activity.object_id, total_comment, comment, gs_sa_user_activity.user_id
            FROM gs_sa_objects  
            INNER JOIN gs_sa_user_activity ON gs_sa_user_activity.object_id = gs_sa_objects.object_id
            WHERE hash = '$hash' AND gs_sa_user_activity.action_type = $action_type
            LIMIT $start,$limit
            ) a
            INNER JOIN $elggUserTable ON $elggUserTable.guid = a.user_id";
        $rs = safe_select_query($q);

        $data = array('users' => array());
        if (!empty($rs)) {
            foreach ($rs as $row) {
                if (!isset($data['object_id'])) {
                    $data['object_id'] = intval($row->object_id);
                }
                if (!isset($data['total_comment'])) {
                    $data['total_comment'] = intval($row->total_comment);
                }
                $data['users'][] = array('user_id' => intval($row->user_id),
                    'name' => $row->name,
                    'comment' => $row->comment,
                    'comment_id' => $row->comment_id
                );
            }
        } else {
            $data['object_id'] = 0;
            $data['total_comment'] = 0;
        }
        return $data;
    }

    ///////////////////////////
    ////////  LIKE  ////////
    ///////////////////////////

    public static function doLike($user_id, $url, $obj_type = GGS_SO_TYPE_LINK, $title = "", $thumb_image = "") {
        return self::updateSocialObjects($user_id, $url, GGS_SA_LIKE, TRUE, 0, '', $obj_type, $title, $thumb_image);
    }

    public static function doUnLike($user_id, $url, $obj_type = GGS_SO_TYPE_LINK) {
        return self::updateSocialObjects($user_id, $url, GGS_SA_LIKE, FALSE, 0, '', $obj_type);
    }

    public static function getTotalLike($url) {
        $hash = self::hashFromUrl($url);
        $rs = safe_select_query("SELECT object_id, total_like FROM gs_sa_objects WHERE hash = '$hash' ");
        if (!empty($rs)) {
            return $rs[0]->total_like;
        }
        return 0;
    }

    public static function getUserLikes($url, $limit = 5) {
        $action_type = GGS_SA_LIKE;
        $hash = self::hashFromUrl($url);
        $elggUserTable = '3lGG_users_entity';

        $q = "SELECT a.*, $elggUserTable.name
            FROM
            (
            SELECT gs_sa_user_activity.object_id, total_like, gs_sa_user_activity.user_id
            FROM gs_sa_objects  
            INNER JOIN gs_sa_user_activity ON gs_sa_user_activity.object_id = gs_sa_objects.object_id
            WHERE hash = '$hash' AND gs_sa_user_activity.action_type = $action_type
            LIMIT $limit
            ) a
            INNER JOIN $elggUserTable ON $elggUserTable.guid = a.user_id";

        $rs = safe_select_query($q);

        $data = array('users' => array());
        if (!empty($rs)) {
            foreach ($rs as $row) {
                if (!isset($data['object_id'])) {
                    $data['object_id'] = intval($row->object_id);
                }
                if (!isset($data['total_like'])) {
                    $data['total_like'] = intval($row->total_like);
                }
                $data['users'][] = array('user_id' => intval($row->user_id), 'name' => $row->name);
            }
        } else {
            $data['object_id'] = 0;
            $data['total_like'] = 0;
        }
        return $data;
    }

}

